package org.example.springmybatisdemo.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.example.springmybatisdemo.entity.*;
//import org.example.springmybatisdemo.exception.BusinessException;
import org.example.springmybatisdemo.mapper.DeptMapper;
import org.example.springmybatisdemo.mapper.EmpMapper;
import org.example.springmybatisdemo.mapper.EmpexprMapper;
import org.example.springmybatisdemo.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.FileNotFoundException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpexprMapper empexprMapper;

    public PageBean pagelist(EmpQueryParam param) {

//        设置分页查
        PageHelper.startPage(param.getPage(), param.getPageSize());
//        调用 mapper查询
        List<Emp> rows = empMapper.pagelist(param);
        Page p = (Page) rows;

        return new PageBean(p.getTotal(),p.getResult());
    }

    @Override
    public EmpLoginInfo login(Emp emp) {
//        1. 添加mapper查询员工
        Emp empDB = empMapper.selectUsernameAndPassword(emp);

//        2. 判断用户名或密码是否正确
        if (empDB != null) {
//            return new EmpLoginInfo(empDB.getId(), empDB.getUsername(), empDB.getName(), null);
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", empDB.getId());
            claims.put("username", empDB.getUsername());
            String token = JwtUtils.generateJwt(claims);
            return new EmpLoginInfo(empDB.getId(), empDB.getUsername(), empDB.getName(), token);
        }
        return null;
    }

    @Transactional(rollbackFor=Exception.class, propagation= Propagation.REQUIRED) // rollbackFor用于控制出现何种异常类型时才回滚事务。REQUIRED默认值，需要事务有则加入 无则创建
    public boolean  addEmp(Emp emp) {
//        1. 补充表缺失的字段
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        log.info("emp:{}", emp);

        // 2. 执行插入并返回结果
        int result = empMapper.insert(emp);

        log.info("id:{}", emp.getId());
        Integer id = emp.getId();
        if(id == null) {
            return false;
        }

//        模拟异常（运行时异常）
//        int i = 1/0;
//        非运行时异常
//        if (true) {
//            throw new RuntimeException("配置文件 config.properties 未找到", new FileNotFoundException("config.properties"));
//        }

//        调用mapper方法，保存员工的工作经历信息到emp_expr表
        List<EmpExpr> empExprList = emp.getEmpExprList();
//        关联员工id
        if (!CollectionUtils.isEmpty(empExprList)) {
            empExprList.forEach((expr) -> {
                expr.setEmpId(id);
            });
//            调用mapper,批量保存员工工作经历数据
            empexprMapper.insertBatch(empExprList);
        }
        return true;

    }
}
